<template>
  <div>
    <!-- 转盘组件 -->
    <div class="rotary" v-if="show">
      <div class="game-content">
        <div class="content">
          <div class="head-sty">
            <div class="record-text" @click="jumpHis">{{ $t('routerTitle.winning_record') }}</div>
            <Icon type="ios-close-circle-outline" class="custom-icon" @click="closeBtn" />
          </div>
          <!-- 底图 -->
          <img :src="activitiesInfo.wheelBackgroundUrl" class="bottom-img" alt="">
          <!-- 抽奖转盘 -->
          <div class="lucky-sty">
            <div class="content-sty">
              <LuckyWheel ref="myLucky" width="23vw" height="23vw" :defaultStyle="defaultStyle" :prizes="prizes"
                :blocks="blocks" @start="startCallback" @end="endCallback" />
              <!-- 转盘按钮-不写在配置项是因为帽子的层级会把转盘压住 -->
              <img :src="activitiesInfo.pointerUrl" class="btn-img" @click="startCallback()" alt="">
            </div>
          </div>
          <!-- 帽子 -->
          <img :src="activitiesInfo.topDecorUrl" class="hat-img" alt="">
        </div>
      </div>
      <t-loading v-if="isLoading" class="pos-sty"></t-loading>
      <div class="handle-sty">
        <router-link :to="`/notice/${activitiesInfo.ruleContentId}`" target="_blank" class="game-desc">
          {{ $t('christmas.instructionsViewActivity') }}
        </router-link>
      </div>
      <div class="play-sty">
        <div class="time-sty">{{ $t('christmas.spinActivity') }} {{ !userInfo ? 1 : timesCount }}</div>
        <div class="invite-sty" @click="shareBtn">{{ $t('personal.invitedUsers') }}</div>
      </div>
    </div>
    <chrims-pop ref="popRef" @againEmit="againEmit"></chrims-pop>
    <share-count ref="copeRef" :textVal="textVal"></share-count>
  </div>
</template>
<script>
import { mapState } from "vuex";
import TLoading from "@/components/t-loading";
import { debounce } from "@/common/common";
import { eventBus } from '@/main'; // 引入全局事件总线
import { listProcessingActivity, getUserDrawCount, userDraw, } from "@/api/user";
import chrimsPop from './chrims-pop.vue';
import ShareCount from "./share-count.vue";
export default {
  props: {
    timesPropCount: {
      type: Number,
      default: 0
    }
  },
  components: { TLoading, chrimsPop, ShareCount },
  data() {
    return {
      show: false,
      isAllowClose: true,//游戏开始不允许点关闭按钮，结束正常点
      blocks: [],
      activitiesInfo: {},
      timesCount: 0,
      prizes: [],
      activityId: '',
      winText: '',//得奖文案
      defaultStyle: {
        // fontSize: '20',
        lineHeight: '18',
        wordWrap: false
      },
      isLoading: false,
      textVal: this.$t('combination.share_get_three_num'),
    }
  },
  computed: {
    ...mapState({
      userInfo: (state) => state.user.userInfo,
    }),
  },
  watch: {
    show(newValue) {
      eventBus.$emit('showMet', newValue);
    },
    activitiesInfo(newValue) {
      if (newValue && newValue.id) {
        this.$emit('activityInfo', newValue)
      }
    },
    timesPropCount: {
      handler(newVal) {
        if (newVal !== null && newVal !== undefined) {
          this.timesCount = newVal;
        }
      },
      immediate: true  // 立即执行一次监听回调，这样首次有值就能赋值
    }
  },
  created() {
    this.activitiesInProgress();//查询进行中的活动
  },
  methods: {
    jumpHis() {
      this.show = false;
      this.$router.push('/user/winningRecord');
    },
    open() {
      this.show = true;
    },
    closeBtn() {
      // 判断是否在游戏过程中，过程中不允许关闭，结束可关闭
      if (this.isAllowClose) {
        this.show = false;
        localStorage.removeItem(`user_${this.userInfo.id}`);
      }
    },
    //查询进行中的活动
    activitiesInProgress() {
      listProcessingActivity().then((res) => {
        let data = res.result;//圣诞节
        data.forEach(item => {
          if (item.activityType === "WHEEL") {
            this.activitiesInfo = item;//活动信息
            this.activityId = item.id;//活动id
            if (this.userInfo) {
              this.getUserTime(item.id);//获取用户抽奖次数
            }
            let newList = item.rewardList;
            this.prizes = newList.map((v, i) => {
              // 如果后台有设置转盘颜色，匹配规则，item.colorOne奇数条颜色 item.colorTwo偶数条颜色
              let background;
              if (v.colorOne) {
                // 判断是否是奇数条数据（索引从0开始，奇数索引对应奇数条）
                background = i % 2 === 1 ? v.colorOne : (v.colorTwo && i % 2 === 0 ? v.colorTwo : '#FFF6D6');
              } else if (v.colorTwo) {
                // 判断是否是偶数条数据（索引从0开始，偶数索引对应偶数条）
                background = i % 2 === 0 ? v.colorTwo : '#FFD1B1';
              } else {
                // 如果后台没配置，前端默认
                background = i % 2 === 1 ? '#FFF6D6' : '#FFD1B1';
              }
              return {
                id: v.sort,
                fonts: [
                  {
                    text: v.rewardName.replace('\\n', '\n'),
                    fontSize: newList.length === 10 ? '15' : '20',
                    top: '20%',
                    fontWeight: '500'
                  }
                ],
                rewardId: v.rewardId,
                background: background
              }
            });
          }
        });
      })
    },
    // 获取用户抽奖次数
    getUserTime(activityId) {
      getUserDrawCount({ activityId: activityId ? activityId : this.activityId }).then((res) => {
        this.timesCount = res.result;
      })
    },
    // 点击抽奖按钮会触发star回调
    startCallback: debounce(function () {
      this.isLoading = true;
      if (this.isAllowClose) {
        // 先判断用户是否登录了，如果未登录跳转到登录页
        if (this.userInfo) {
          userDraw({ activityId: this.activityId }).then((res) => {
            this.isLoading = false;
            this.timesCount = res.result.userDrawCount;//更新次数
            // 失败类型 1-活动结束 2-活动暂停 3-没有抽奖次数 4-奖品池已空	
            if (res.result.failType) {
              this.$refs.popRef.open({ type: res.result.failType });
            } else {
              // 调用抽奖组件的play方法开始游戏
              this.$refs.myLucky.play();
              // 抽奖过程中禁止关闭
              this.isAllowClose = false;//不允许点击关闭按钮
              // 模拟调用接口异步抽奖
              setTimeout(() => {
                this.prizes.forEach((item, index) => {
                  if (res.result.rewardId === item.rewardId) {
                    this.winText = item.fonts[0].text;//中奖文案
                    // 调用stop停止旋转并传递中奖索引
                    this.$refs.myLucky.stop(index)
                  }
                });
              }, 3000)
            }
          })
        } else {
          this.$router.push('/login');
        }
      }
    }),
    // 抽奖结束会触发end回调
    endCallback(prize) {
      // 抽奖过程中禁止关闭
      this.isAllowClose = true;//允许点击关闭按钮
      this.show = false;
      // 抽奖结束显示结果弹窗
      this.$refs.popRef.open({ type: 0, text: this.winText });
    },
    againEmit() {
      this.show = true;
    },
    shareBtn() {
      this.$refs.copeRef.open();
    }
  }
}
</script>
<style lang="less" scoped>
.rotary {
  width: 100vw;
  height: 100vh;
  background-color: #00000080;
  position: fixed;
  left: 0;
  top: 0;
  z-index: 1001;

  .pos-sty {
    position: absolute;
    top: 45%;
    left: 0;
    z-index: 1002;
  }

  .game-content {
    width: 100%;
    height: 90%;
    display: flex;
    justify-content: center;
    align-items: center;

    .content {
      width: 650px;
      height: 780px;
      position: relative;

      .bottom-img {
        width: 100%;
        height: 100%;
      }

      .head-sty {
        width: 100%;
        position: absolute;
        top: -25px;
        z-index: 2000;
        display: flex;
        align-items: center;
        justify-content: space-between;

        .record-text {
          font-family: PingFang SC, PingFang SC;
          font-weight: 600;
          font-size: 20px;
          color: #FFFFFF;
          line-height: 34px;
          padding-bottom: 2px;
          border-bottom: 1px solid #FFFFFF;
          cursor: pointer;
        }

        .custom-icon {
          color: #FFFFFF;
          font-size: 38px;
          cursor: pointer;
        }
      }

      .hat-img {
        width: 650px;
        position: absolute;
        top: 0;
        left: 0;
        right: 0;
      }

      .lucky-sty {
        position: absolute;
        top: 0;
        left: 0;
        right: 0;
        bottom: 0;
        display: flex;
        justify-content: center;
        align-items: center;
        margin-top: 84px;

        .content-sty {
          position: relative;

          .btn-img {
            height: 173px;
            position: absolute;
            top: 120px;
            left: 0;
            right: 0;
            margin: 0 auto;
            z-index: 99;
            cursor: pointer;
          }
        }
      }
    }
  }

  .handle-sty {
    display: flex;
    justify-content: center;
    margin-top: -110px;
    position: relative;
    z-index: 99;

    .game-desc {
      font-family: PingFang SC, PingFang SC;
      font-weight: 600;
      font-size: 18px;
      color: #FFFFFF;
      line-height: 31px;
      padding-bottom: 1px;
      border-bottom: 1px solid #FFFFFF;
      cursor: pointer;
    }
  }

  .play-sty {
    display: flex;
    justify-content: center;
    gap: 24px;
    margin-top: 14px;

    .time-sty {
      min-width: 270px;
      height: 77px;
      background-image: url('@/assets/images/activity/rotary_time.png');
      background-repeat: no-repeat;
      background-size: 100% 100%;
      font-family: Open Sans, Open Sans;
      font-weight: 600;
      font-size: 20px;
      color: #FFFFFF;
      text-align: center;
      padding-top: 35px;
      padding-right: 10px;
      padding-left: 20px;
    }

    .invite-sty {
      min-width: 270px;
      height: 77px;
      background-image: url('@/assets/images/activity/rotary_invite.png');
      background-repeat: no-repeat;
      background-size: 100% 100%;
      font-family: Open Sans, Open Sans;
      font-weight: 600;
      font-size: 20px;
      color: #FFFFFF;
      text-align: center;
      padding-top: 35px;
      padding-right: 10px;
      padding-left: 20px;
      cursor: pointer;
    }
  }
}
</style>
